import axios from 'axios';
import { Message } from 'element-ui';
import router from '@/router';

// create an axios instance
const service = axios.create({
  baseURL: '/api',
  timeout: 5000,
})

// 请求拦截
service.interceptors.request.use(
  config => {
    // 取token
    config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
    return config
  },
  error => {
    console.log(error) // for debug
    return Promise.reject(error)
  },
);

// response interceptor
// 响应拦截
service.interceptors.response.use(
  res => res,
  error => {
    console.dir(error) // for debug

    switch (error.response.status) {
      case 401:
        router.push('/login');
        break;

      // more http status code here

      default:
        break;
    }

    Message({
      message: error.message,
      type: 'error',
      duration: 1000,
    });
    // return Promise.reject(error);
    return error;
  },
);

export default service
